﻿namespace WMS6.SQLServerDAL
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Data.SqlClient;
    using System.Text;
    using WMS6.Common;
    using WMS6.DataEntity;
    using WMS6.DBUtility;
    using WMS6.IDAL;
    using WMS6.QueryEntity;

    public class UserCustomerDA : IUserCustomerDA
    {
        private string CREATED_BY = "@CREATED_BY";
        private string CUSTOMER_ID = "@CUSTOMER_ID";
        private string IS_DEFAULT = "@IS_DEFAULT";
        private string SQL_CHECK_USER_CUSTOMER_ID_UNIQUE = " SELECT COUNT(1) FROM @_@USER_CUSTOMER WHERE USER_ID = @USER_ID AND CUSTOMER_ID = @CUSTOMER_ID ";
        private string SQL_DELETE_USER_CUSTOMER = " DELETE FROM @_@USER_CUSTOMER WHERE USER_ID = @USER_ID ";
        private string SQL_INSERT_USER_CUSTOMER = " INSERT INTO @_@USER_CUSTOMER ( USER_ID, CUSTOMER_ID, IS_DEFAULT, CREATED_BY, CREATED_DATE, UPDATED_BY,UPDATED_DATE) VALUES ( @USER_ID, @CUSTOMER_ID, @IS_DEFAULT, @CREATED_BY, GETDATE(), @UPDATED_BY,  GETDATE())  ";
        private string SQL_SELECT_ALL_USER_CUSTOMER = " SELECT  ROWID, USER_ID, CUSTOMER_ID, IS_DEFAULT, TS, CREATED_BY, CREATED_DATE, UPDATED_BY,UPDATED_DATE  FROM  @_@USER_CUSTOMER ";
        private string SQL_UPDATE_USER_CUSTOMER = " UPDATE @_@USER_CUSTOMER SET IS_DEFAULT = @IS_DEFAULT, UPDATED_BY = @UPDATED_BY,UPDATED_DATE=GETDATE()  WHERE USER_ID = @USER_ID AND CUSTOMER_ID = @CUSTOMER_ID  ";
        private string TS = "@TS";
        private string UPDATED_BY = "@UPDATED_BY";
        private string USER_ID = "@USER_ID";

        public bool CheckUserCustomerIDUnique(string userID, string CustomerID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID), new SqlParameter("@CUSTOMER_ID", CustomerID) };
            return (DBHelper.ExecuteScalar(CommandType.Text, this.SQL_CHECK_USER_CUSTOMER_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public bool CheckUserCustomerIDUnique(DataBase dataBase, DbTransaction tran, string userID, string CustomerID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID), new SqlParameter("@CUSTOMER_ID", CustomerID) };
            return (dataBase.ExecuteScalar(tran, CommandType.Text, this.SQL_CHECK_USER_CUSTOMER_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public int DeleteUserCustomer(string userID, string CustomerID, string whLoginID)
        {
            int result = 0;
            string strSql = this.SQL_DELETE_USER_CUSTOMER.Replace("@_@", whLoginID) + "AND CUSTOMER_ID = @CUSTOMER_ID";
            DataBase dataBase = new DataBase();
            DbConnection conn = dataBase.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID), new SqlParameter("@CUSTOMER_ID", CustomerID) };
                result += dataBase.ExecuteNonQuery(tran, CommandType.Text, strSql, paras);
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int DeleteUserCustomer(DataBase dataBase, DbTransaction tran, string userID, string whLoginID)
        {
            int result = 0;
            try
            {
                SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID) };
                result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_DELETE_USER_CUSTOMER.Replace("@_@", whLoginID), paras);
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int DeleteUserCustomer(DataBase dataBase, DbTransaction tran, string userID, string CustomerID, string whLoginID)
        {
            string strSql = this.SQL_DELETE_USER_CUSTOMER.Replace("@_@", whLoginID) + "AND CUSTOMER_ID = @CUSTOMER_ID";
            int result = 0;
            try
            {
                SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID), new SqlParameter("@CUSTOMER_ID", CustomerID) };
                result += dataBase.ExecuteNonQuery(tran, CommandType.Text, strSql, paras);
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int DeleteUserCustomerByCustomerID(DataBase dataBase, DbTransaction tran, string customerID, string whLoginID)
        {
            int result = 0;
            try
            {
                string StrSql = " DELETE FROM SYSADM.USER_CUSTOMER WHERE CUSTOMER_ID = '" + customerID + "'";
                result += dataBase.ExecuteNonQuery(tran, CommandType.Text, StrSql);
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public DataSet GetAllUserCustomer(string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_USER_CUSTOMER.Replace("@_@", whLoginID);
            return DBHelper.ExecuteDataSet(CommandType.Text, sql);
        }

        public DataSet GetAllUserCustomer(DataBase dataBase, DbTransaction tran, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_USER_CUSTOMER.Replace("@_@", whLoginID);
            return dataBase.ExecuteDataSet(tran, CommandType.Text, sql);
        }

        public DataSet GetAuthorizationUserByCustomerID(string customerID, string whLoginID)
        {
            StringBuilder StrSql = new StringBuilder();
            StrSql.AppendFormat("SELECT UM.USER_ID,UM.USER_NAME, CASE LEN(ISNULL(UC.USER_ID,''))  WHEN 0 THEN 'N' ELSE 'Y' END AS PREMISSION_USER FROM SYSADM.USER_MST UM LEFT JOIN SYSADM.USER_CUSTOMER UC ON UM.USER_ID = UC.USER_ID AND UC.CUSTOMER_ID = '{0}'", customerID);
            return DBHelper.ExecuteDataSet(CommandType.Text, StrSql.ToString());
        }

        public List<UserCustomerInfo> GetAuthorizedCustomerByUserID(string userID, string whLoginID)
        {
            List<UserCustomerInfo> UserCustomerList = new List<UserCustomerInfo>();
            StringBuilder StrSql = new StringBuilder();
            StrSql.AppendFormat("SELECT  C.CUSTOMER_ID,C.COMPANY,UC.IS_DEFAULT FROM {1}CUSTOMER C  INNER JOIN  SYSADM.USER_CUSTOMER UC ON C.CUSTOMER_ID = UC.CUSTOMER_ID WHERE UC.USER_ID='{0}'", userID, whLoginID);
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, StrSql.ToString()))
            {
                UserCustomerInfo userCustomerInfo = null;
                while (reader.Read())
                {
                    userCustomerInfo = new UserCustomerInfo(reader["CUSTOMER_ID"].ToString(), reader["COMPANY"].ToString(), reader["IS_DEFAULT"].ToString());
                    UserCustomerList.Add(userCustomerInfo);
                }
            }
            return UserCustomerList;
        }

        public UserCustomerInfo GetCustomerByUserID(string userID)
        {
            StringBuilder StrSql = new StringBuilder();
            StrSql.AppendFormat("SELECT CUSTOMER_ID,IS_DEFAULT FROM SYSADM.USER_CUSTOMER WHERE IS_DEFAULT='Y' AND USER_ID='{0}'", userID);
            UserCustomerInfo userCustomerInfo = new UserCustomerInfo();
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, StrSql.ToString()))
            {
                while (reader.Read())
                {
                    userCustomerInfo = new UserCustomerInfo(reader["CUSTOMER_ID"].ToString(), "", reader["IS_DEFAULT"].ToString());
                }
            }
            return userCustomerInfo;
        }

        public List<UserCustomerInfo> GetUnauthorizedCustomerByUserID(string userID, string whLoginID)
        {
            List<UserCustomerInfo> UserCustomerList = new List<UserCustomerInfo>();
            StringBuilder StrSql = new StringBuilder();
            StrSql.AppendFormat("   SELECT  C.CUSTOMER_ID,C.COMPANY, ''AS IS_DEFAULT  FROM {1}CUSTOMER C  WHERE C.CUSTOMER_ID NOT IN( SELECT CUSTOMER_ID FROM SYSADM.USER_CUSTOMER WHERE USER_ID='{0}')", userID, whLoginID);
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, StrSql.ToString()))
            {
                UserCustomerInfo userCustomerInfo = null;
                while (reader.Read())
                {
                    userCustomerInfo = new UserCustomerInfo(reader["CUSTOMER_ID"].ToString(), reader["COMPANY"].ToString(), reader["IS_DEFAULT"].ToString());
                    UserCustomerList.Add(userCustomerInfo);
                }
            }
            return UserCustomerList;
        }

        public UserCustomerInfo GetUserCustomerByID(string userID, string customerID, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_USER_CUSTOMER.Replace("@_@", whLoginID) + " WHERE USER_ID = @USER_ID AND CUSTOMER_ID = @CUSTOMER_ID  ";
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID), new SqlParameter("@CUSTOMER_ID", customerID) };
            UserCustomerInfo userCustomerInfo = null;
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, sql, paras))
            {
                if (reader.Read())
                {
                    userCustomerInfo = new UserCustomerInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["USER_ID"].ToString(), reader["CUSTOMER_ID"].ToString(), reader["IS_DEFAULT"].ToString(), (byte[]) reader["TS"], reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : new DateTime(), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : new DateTime());
                }
            }
            return userCustomerInfo;
        }

        public UserCustomerInfo GetUserCustomerByID(DataBase dataBase, DbTransaction tran, string userID, string customerID, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_USER_CUSTOMER.Replace("@_@", whLoginID) + " WHERE USER_ID = @USER_ID AND CUSTOMER_ID = @CUSTOMER_ID  ";
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID), new SqlParameter("@CUSTOMER_ID", customerID) };
            UserCustomerInfo userCustomerInfo = null;
            IDataReader reader = dataBase.ExecuteReader(tran, CommandType.Text, sql, paras);
            if (reader.Read())
            {
                userCustomerInfo = new UserCustomerInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["USER_ID"].ToString(), reader["CUSTOMER_ID"].ToString(), reader["IS_DEFAULT"].ToString(), (byte[]) reader["TS"], reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : new DateTime(), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : new DateTime());
            }
            if (!reader.IsClosed)
            {
                reader.Close();
            }
            return userCustomerInfo;
        }

        public DataSet GetUserCustomerByQueryList(List<string> sqlWhere, UserCustomerQueryEntity uservendorQuery, string whLoginID)
        {
            string temp = this.SQL_SELECT_ALL_USER_CUSTOMER.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            if (!uservendorQuery.IsGetAll)
            {
                temp = PagingHelper.GetPagingSQL(temp, uservendorQuery.CurrentPage, uservendorQuery.PageSize, uservendorQuery.SortField, uservendorQuery.SortDirection);
            }
            return DBHelper.ExecuteDataSet(CommandType.Text, temp);
        }

        public DataSet GetUserCustomerByQueryList(DataBase dataBase, DbTransaction tran, List<string> sqlWhere, UserCustomerQueryEntity uservendorQuery, string whLoginID)
        {
            string temp = this.SQL_SELECT_ALL_USER_CUSTOMER.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            temp = PagingHelper.GetPagingSQL(temp, uservendorQuery.CurrentPage, uservendorQuery.PageSize, uservendorQuery.SortField, uservendorQuery.SortDirection);
            return dataBase.ExecuteDataSet(tran, CommandType.Text, temp);
        }

        public List<UserCustomerInfo> GetUserCustomerInfoByCustomerIDandUserID(string customerID, string whLoginID)
        {
            StringBuilder StrSql = new StringBuilder();
            string sql = this.SQL_SELECT_ALL_USER_CUSTOMER.Replace("@_@", whLoginID) + "WHERE CUSTOMER_ID = '{0}'";
            StrSql.AppendFormat(sql, customerID);
            List<UserCustomerInfo> userCustomerListInfo = new List<UserCustomerInfo>();
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, StrSql.ToString()))
            {
                UserCustomerInfo userCustomerInfo = null;
                while (reader.Read())
                {
                    DateTime CS00001;
                    userCustomerInfo = new UserCustomerInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["USER_ID"].ToString(), reader["CUSTOMER_ID"].ToString(), reader["IS_DEFAULT"].ToString(), (byte[]) reader["TS"], reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : (CS00001 = new DateTime()), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : (CS00001 = new DateTime()));
                    userCustomerListInfo.Add(userCustomerInfo);
                }
            }
            return userCustomerListInfo;
        }

        public List<UserCustomerInfo> GetUserCustomerInfoByCustomerIDandUserID(DataBase dataBase, DbTransaction tran, string customerID, string whLoginID)
        {
            StringBuilder StrSql = new StringBuilder();
            string sql = this.SQL_SELECT_ALL_USER_CUSTOMER.Replace("@_@", whLoginID) + "WHERE CUSTOMER_ID = '{0}'";
            StrSql.AppendFormat(sql, customerID);
            List<UserCustomerInfo> userCustomerListInfo = new List<UserCustomerInfo>();
            using (IDataReader reader = dataBase.ExecuteReader(tran, CommandType.Text, StrSql.ToString()))
            {
                UserCustomerInfo userCustomerInfo = null;
                while (reader.Read())
                {
                    DateTime CS00001;
                    userCustomerInfo = new UserCustomerInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["USER_ID"].ToString(), reader["CUSTOMER_ID"].ToString(), reader["IS_DEFAULT"].ToString(), (byte[]) reader["TS"], reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : (CS00001 = new DateTime()), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : (CS00001 = new DateTime()));
                    userCustomerListInfo.Add(userCustomerInfo);
                }
            }
            return userCustomerListInfo;
        }

        public int InsertUserCustomer(UserCustomerInfo userCustomerInfo, string whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                SqlParameter[] paras = this.Set_UserCustomer_Parameters(userCustomerInfo);
                if (paras != null)
                {
                    result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_USER_CUSTOMER.Replace("@_@", whLoginID), paras);
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int InsertUserCustomer(DataBase dataBase, DbTransaction tran, UserCustomerInfo userCustomerInfo, string whLoginID)
        {
            int result = 0;
            try
            {
                SqlParameter[] paras = this.Set_UserCustomer_Parameters(userCustomerInfo);
                if (paras != null)
                {
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_USER_CUSTOMER.Replace("@_@", whLoginID), paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int InsertUserCustomerByCustomerID(DataBase dataBase, DbTransaction tran, List<UserCustomerInfo> userCustomerListInfo, string whLoginID)
        {
            int result = 0;
            try
            {
                foreach (UserCustomerInfo userCustomerInfo in userCustomerListInfo)
                {
                    SqlParameter[] paras = this.Set_UserCustomer_Parameters(userCustomerInfo);
                    if (paras != null)
                    {
                        result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_USER_CUSTOMER.Replace("@_@", whLoginID), paras);
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        private SqlParameter[] Set_UserCustomer_Parameters(UserCustomerInfo userCustomerInfo)
        {
            SqlParameter[] paramArray = new SqlParameter[] { new SqlParameter(this.USER_ID, SqlDbType.VarChar, 20), new SqlParameter(this.CUSTOMER_ID, SqlDbType.VarChar, 20), new SqlParameter(this.IS_DEFAULT, SqlDbType.VarChar, 1), new SqlParameter(this.CREATED_BY, SqlDbType.VarChar, 20), new SqlParameter(this.UPDATED_BY, SqlDbType.VarChar, 20) };
            paramArray[0].Value = userCustomerInfo.UserID;
            paramArray[1].Value = userCustomerInfo.CustomerID;
            if (!string.IsNullOrEmpty(userCustomerInfo.IsDefault))
            {
                paramArray[2].Value = userCustomerInfo.IsDefault;
            }
            else
            {
                paramArray[2].Value = DBNull.Value;
            }
            paramArray[3].Value = userCustomerInfo.CreatedBy;
            paramArray[4].Value = userCustomerInfo.UpdatedBy;
            return paramArray;
        }

        public int UpdateUserCustomer(UserCustomerInfo userCustomerInfo, string whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                SqlParameter[] paras = this.Set_UserCustomer_Parameters(userCustomerInfo);
                if (paras != null)
                {
                    result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_USER_CUSTOMER.Replace("@_@", whLoginID), paras);
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int UpdateUserCustomer(DataBase dataBase, DbTransaction tran, UserCustomerInfo userCustomerInfo, string whLoginID)
        {
            int result = 0;
            try
            {
                SqlParameter[] paras = this.Set_UserCustomer_Parameters(userCustomerInfo);
                if (paras != null)
                {
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_USER_CUSTOMER.Replace("@_@", whLoginID), paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }
    }
}

